/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.core.services;

import java.util.HashSet;
import javax.jcr.RepositoryException;
import javax.jcr.Value;
import javax.jcr.ValueFactory;
import javax.jcr.ValueFormatException;

/**
 *
 * @author Walter L�tgenau
 */
public class ValueExtender {
    ValueFactory factory;

    public ValueExtender(ValueFactory factory) {
        this.factory = factory;
    }
    /**
     * Add a value to a value array.
     *
     * @param existingValues
     * @param additionalValue
     * @return
     */
    protected Value[] addValue(Value[] existingValues, Value additionalValue) {
        Value[] result = new Value[existingValues.length+1];
        for (int i = 0; i < existingValues.length; i++)
            result[i] = existingValues[i];
        result[result.length-1] = additionalValue;

        return result;
    }

    /**
     * Add values to the corresponding multi value property, if not already present.
     *
     * To guarantee a common value type, all values are converted to string.
     *
     * @param node
     * @param propertyName
     * @param additionalValues
     * @throws RepositoryException
     */
    public Value[] addValues(Value[] values, Value[] additionalValues) throws RepositoryException {
        values = convertToString(values);
        additionalValues = convertToString(additionalValues);

        HashSet<String> existingValues = new HashSet<String>();
        for (Value value : values)
            existingValues.add(value.getString());

        for (Value value : additionalValues)
            if (!existingValues.contains(value.getString()))
                values = addValue(values, value);

        return values;
    }

    /**
     * Convert a value array of any type to a string value array.
     * 
     * @param values
     * @return
     * @throws RepositoryException
     */
    public Value[] convertToString(Value[] values) throws RepositoryException {
        Value[] result = new Value[values.length];

        for (int i = 0; i < result.length; i++)
            result[i] = factory.createValue(values[i].getString());

        return result;
    }

}
